package com.example.hcd.functionactivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hcd.MenuActivity;
import com.example.hcd.R;
import com.example.hcd.adapt.FileAdapter;
import com.example.hcd.datamanage.LoadedImage;
import com.example.hcd.datamanage.PeopleNextData;
import com.example.hcd.datamanage.UseCarData;
import com.example.hcd.datamanage.UserInfo;
import com.example.hcd.datamanage.UserInfoData;
import com.example.hcd.internet.FileUtils;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;
import com.example.hcd.tool.MyGridView;
import com.example.hcd.tool.MyLoadingDialog;
import com.example.hcd.tool.SelectPersonPop;
import com.example.hcd.tool.ToastHelp;
import com.wheel.StrericWheelAdapter;
import com.wheel.WheelView;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Calendar;

/**
 * Created by Dell on 2016/8/10.
 */
public class UseCarApply extends BaseActivity implements View.OnClickListener {

    private UseCarApply context;
    private EditText titleEdit,nameEdit,dirEdit,reasonEdit,milesageEdit,remarkEdit,nextPeopleEdit;
    private TextView timeText;
    // 附件的GridView
    private MyGridView gridview;

    // 附件的地址集合
    private ArrayList<String> listfile = new ArrayList<String>();
    private ArrayList<String> listfileCatch = new ArrayList<String>();

    private FileAdapter fileAdapter;

    // 获取下一步处理人
    private ArrayList<PeopleNextData> peoples_next;
    private TextView nextPeople;

    private RelativeLayout nextPeopleBg;


    private UseCarData useCarData =new UseCarData();



    //滚动时间
    private WheelView yearWheel,monthWheel,dayWheel,hourWheel,minuteWheel;
    public static String[] yearContent=null;
    public static String[] monthContent=null;
    public static String[] dayContent=null;
    public static String[] hourContent = null;
    public static String[] minuteContent=null;

    private  SelectPersonPop selectPersonPop;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.usecar_apply_view);
        context = this;

        initContent();
        initView();
    }

    public void initContent()
    {
        yearContent = new String[10];
        for(int i=0;i<10;i++)
            yearContent[i] = String.valueOf(i+2013);

        monthContent = new String[12];
        for(int i=0;i<12;i++)
        {
            monthContent[i]= String.valueOf(i+1);
            if(monthContent[i].length()<2)
            {
                monthContent[i] = "0"+monthContent[i];
            }
        }

        dayContent = new String[31];
        for(int i=0;i<31;i++)
        {
            dayContent[i]=String.valueOf(i+1);
            if(dayContent[i].length()<2)
            {
                dayContent[i] = "0"+dayContent[i];
            }
        }
        hourContent = new String[24];
        for(int i=0;i<24;i++)
        {
            hourContent[i]= String.valueOf(i);
            if(hourContent[i].length()<2)
            {
                hourContent[i] = "0"+hourContent[i];
            }
        }

        minuteContent = new String[2];
        for(int i=0;i<2;i++)
        {
//			minuteContent[i]=String.valueOf(i);
//			if(minuteContent[i].length()<2)
//	        {
//				minuteContent[i] = "0"+minuteContent[i];
//	        }
            if(i==0)
            {
                minuteContent[i]="00";
            }else
            {
                minuteContent[i]="30";
            }

        }
    }


    private void initView() {
        titleEdit =(EditText)findViewById(R.id.editText);
        nameEdit =(EditText)findViewById(R.id.useNameEditText);
        dirEdit =(EditText)findViewById(R.id.dirEditText);
        reasonEdit =(EditText)findViewById(R.id.reasonEditText);
        milesageEdit =(EditText)findViewById(R.id.mileageEditText);
        timeText =(TextView)findViewById(R.id.timeText);
        remarkEdit =(EditText)findViewById(R.id.editText9);
        nextPeopleEdit =(EditText)findViewById(R.id.next_people);

        timeText.setOnClickListener(context);



        nameEdit.setText(UserInfo.getUserInfor().getName());
        UserInfoData data =new UserInfoData();
        data.name =UserInfo.getUserInfor().getName();
        data.id =UserInfo.getUserInfor().getId();
        nameEdit.setTag(data);

        nameEdit.addTextChangedListener(filterTextWatcher);

        selectPersonPop =new SelectPersonPop(this, nameEdit, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UserInfoData data =(UserInfoData)parent.getAdapter().getItem(position);
                Log.e("data",data.name);
                nameEdit.removeTextChangedListener(filterTextWatcher);
                nameEdit.setText(data.name);
                nameEdit.addTextChangedListener(filterTextWatcher);
                nameEdit.setTag(data);
                selectPersonPop.dismiss();
            }
        });

        ImageView backBtn = (ImageView) findViewById(R.id.title_bar_btn_left);
        // 提交键
        ImageView uploadBtn = (ImageView) findViewById(R.id.title_bar_btn_right);
        backBtn.setOnClickListener(context);
        uploadBtn.setOnClickListener(context);

        gridview = (MyGridView) findViewById(R.id.file_gridview);
        gridview.setVisibility(View.GONE);
        fileAdapter = new FileAdapter(this);
        gridview.setAdapter(fileAdapter);

        gridview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            // GridList长按了某项
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // 这里的arg2代表长按的位置
                fileAdapter.photos.remove(arg2);// 移除数据
                listfile.remove(arg2);

                if (fileAdapter.photos.size() == 0) {
                    gridview.setVisibility(View.GONE);
                }

                fileAdapter.notifyDataSetInvalidated();

                return true;
            }
        });

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // TODO Auto-generated method stub
                LoadedImage uri = fileAdapter.getItem(arg2);
                // System.out.println(uri.getText());

                if (FileUtils.isPic(getLast(uri.getPicPath()))) {
                    ArrayList<String> picpathlist = new ArrayList<String>();
                    Intent intent = new Intent(UseCarApply.this, ShowPictureList.class);
                    for (int i = 0; i < listfile.size(); i++) {
                        if (FileUtils.isPic(listfile.get(i))) {
                            picpathlist.add(listfile.get(i));
                        }
                    }

                    for (int i = 0; i < picpathlist.size(); i++) {
                        if (picpathlist.get(i).equals(uri.getPicPath())) {
                            intent.putExtra("MOREN_INDEX", i);
                        }
                    }

                    intent.putStringArrayListExtra("PICK_PATH_LIST", picpathlist);

                    intent.putExtra("IS_BENDI", true);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(UseCarApply.this, FileDetailActivity.class);
                    intent.putExtra("FILE_URI", uri.getPicPath());
                    intent.putExtra("FILE_NAME", getLast(uri.getPicPath()));
                    intent.putExtra("IS_BENDI", true);
                    startActivity(intent);
                }

                overridePendingTransition(R.anim.out_alpha, R.anim.enter_alpha);
            }
        });

        ImageView appendix_btn = (ImageView) findViewById(R.id.appendix_btn);
        appendix_btn.setOnClickListener(this);


        // 获取下一步处理人
        nextPeopleBg = (RelativeLayout) findViewById(R.id.next_people_bg);
        nextPeople = (TextView) findViewById(R.id.next_people);
        peoples_next = new ArrayList<PeopleNextData>();
        // 获取下一步处理人
        getNextPeople next = new getNextPeople();
        next.execute();

    }

    private TextWatcher filterTextWatcher = new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
                  selectPersonPop.filterWords(s);

//            listAdapter.getFilter().filter(s); //这里传入数据就可以了
        }

    };

    public boolean isCanUpload() {
        if(nameEdit.getText()!=null&&!nameEdit.getText().equals("")) {
            UserInfoData data =(UserInfoData) nameEdit.getTag();
            useCarData.setUserName(data.name);
            useCarData.setUserId(data.id);
        }else
        {
            ToastHelp.doToast(context,"请填写用车人姓名！");
            return false;
        }
        if(dirEdit.getText().toString()!=null&!dirEdit.getText().toString().equals("")) {
            useCarData.setDestination(dirEdit.getText().toString());
        }else
        {
            ToastHelp.doToast(context,"请填写用车人姓名！");
            return false;
        }
        if(milesageEdit.getText().toString()!=null&&!milesageEdit.getText().toString().equals("")) {
            useCarData.setPredictMileage(Integer.parseInt(milesageEdit.getText().toString()));
        }else
        {
            ToastHelp.doToast(context,"请填写用预计里程！");
            return false;
        }
        if(reasonEdit.getText().toString()!=null&&!reasonEdit.getText().toString().equals("")) {
            useCarData.setReason(reasonEdit.getText().toString());
        }else
        {
            ToastHelp.doToast(context,"请填写用用车事由！");
            return false;
        }
        if(timeText.getText().toString()!=null&&!timeText.getText().toString().equals("")) {
            useCarData.setStartData(timeText.getText().toString());
        }else
        {
            ToastHelp.doToast(context,"请填写用出车时间！");
            return false;
        }

        useCarData.setRemark(remarkEdit.getText().toString());


        return true;
    }


    // 获取下一步处理人
    private class getNextPeople extends AsyncTask<String, Integer, String> {

        // private ProgressDialog mProgress;
        public getNextPeople() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            HttpResponse response = null;
            BufferedReader reader = null;
            try {
                ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
                vs.add(new BasicNameValuePair("taskId", ""));
                response = LinkHelp.post(URLS.getNextWorkUser("outgoing"), vs, false);

                if (response != null) {
                    StatusLine line = response.getStatusLine();
                    if (line.getStatusCode() == 200) {
                        reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                        StringBuilder sb = new StringBuilder();
                        for (String s = reader.readLine(); s != null; s = reader.readLine()) {
                            sb.append(s);
                        }
                        reader.close();
                        result = sb.toString();

                        System.out.println(result);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {

            if (result == null) {
                ToastHelp.doToast(context, "网络异常！");
                return;
            }

            JSONObject jsonObject;
            try {
                jsonObject = new JSONObject(result);
                if (jsonObject.isNull("code")) {
                    String status = jsonObject.getString("status");
                    if (status.equals("success")) {
                        {
                            if (result.contains("workUserInfo")) {
                                JSONArray peoples = jsonObject.getJSONArray("workUserInfo");
                                for (int i = 0; i < peoples.length(); i++) {
                                    PeopleNextData data = new PeopleNextData();
                                    JSONObject myJS = peoples.getJSONObject(i);
                                    data.setUserId(myJS.getString("userId"));
                                    data.setUserName(myJS.getString("userName"));
                                    data.setDepartmentId(myJS.getString("departmentId"));
                                    data.setDepartmentName(myJS.getString("departmentName"));
                                    data.setCompanyId(myJS.getString("companyId"));
                                    data.setCompanyName(myJS.getString("companyName"));
                                    data.setIsHead(myJS.getString("isHead"));
                                    data.setCode(myJS.getString("code"));
                                    peoples_next.add(data);
                                }
                                if (peoples_next.size() >= 1) {
                                    nextPeople.setText(peoples_next.get(0).getUserName() + "("
                                            + peoples_next.get(0).getDepartmentName() + ")");
                                } else {
                                    nextPeopleBg.setVisibility(View.GONE);
                                }

                            } else if (result.contains("noNeedWorkUserId")) {
                                if (jsonObject.getString("noNeedWorkUserId").equals("true")) {
                                    nextPeople.setText("下一步不需要处理人");
                                    nextPeopleBg.setVisibility(View.GONE);
                                }

                            } else if (result.contains("msg")) {
                                nextPeople.setText(jsonObject.getString("msg"));

                                if (jsonObject.getString("msg").contains("不需要")) {
                                    nextPeopleBg.setVisibility(View.GONE);
                                }

                            } else {
                                System.out.println("Shit!服务器给的什么破数据");
                            }

                        }

                    } else {
                        String msg = jsonObject.getString("msg");
                        // Toast.makeText(context, msg,
                        // Toast.LENGTH_SHORT).show();
                        ToastHelp.doToastInTop(context, msg);
                        nextPeople.setText("空");
                        nextPeopleBg.setVisibility(View.GONE);
                    }

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    private String getLast(String path) {
        String a[] = path.split("/");
        return a[a.length - 1];
    }



    @Override
    public void onClick(View v) {
       switch (v.getId())
       {
           case R.id.appendix_btn:
               Intent intent = new Intent(UseCarApply.this, SelectPicActivity.class);
               intent.putExtra("type", "choosemore");
               intent.putExtra("IS_CHOOSE_FILE", true);
               startActivityForResult(intent, MenuActivity.SELECT_PHOTO);
               overridePendingTransition(R.anim.out_alpha, R.anim.enter_alpha);
               break;

           case R.id.title_bar_btn_left:
               finish();
               break;

           case R.id.title_bar_btn_right:
               upload();
               break;

           case R.id.timeText:
               final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
               Window window = alertDialog.getWindow();
               window.setGravity(Gravity.BOTTOM);
               window.setWindowAnimations(R.style.pop_float_win_anim_style);
               alertDialog.setCanceledOnTouchOutside(true);
               alertDialog.show();
               window.setContentView(R.layout.custom_alert_dialog);
               View view = window.findViewById(R.id.time_picker);

               Calendar calendar = Calendar.getInstance();
               int curYear = calendar.get(Calendar.YEAR);
               int curMonth= calendar.get(Calendar.MONTH)+1;
               int curDay = calendar.get(Calendar.DAY_OF_MONTH);
               int curHour = calendar.get(Calendar.HOUR_OF_DAY);
               int curMinute = calendar.get(Calendar.MINUTE);

               yearWheel = (WheelView)view.findViewById(R.id.yearwheel);
               monthWheel = (WheelView)view.findViewById(R.id.monthwheel);
               dayWheel = (WheelView)view.findViewById(R.id.daywheel);
               hourWheel = (WheelView)view.findViewById(R.id.hourwheel);
               minuteWheel = (WheelView)view.findViewById(R.id.minutewheel);



               yearWheel.setAdapter(new StrericWheelAdapter(yearContent));
               yearWheel.setCurrentItem(curYear-2013);
               yearWheel.setCyclic(true);
               yearWheel.setInterpolator(new AnticipateOvershootInterpolator());


               monthWheel.setAdapter(new StrericWheelAdapter(monthContent));

               monthWheel.setCurrentItem(curMonth-1);

               monthWheel.setCyclic(true);
               monthWheel.setInterpolator(new AnticipateOvershootInterpolator());

               dayWheel.setAdapter(new StrericWheelAdapter(dayContent));
               dayWheel.setCurrentItem(curDay-1);
               dayWheel.setCyclic(true);
               dayWheel.setInterpolator(new AnticipateOvershootInterpolator());

               hourWheel.setAdapter(new StrericWheelAdapter(hourContent));
               hourWheel.setCurrentItem(curHour);
               hourWheel.setCyclic(true);
               hourWheel.setInterpolator(new AnticipateOvershootInterpolator());

               minuteWheel.setAdapter(new StrericWheelAdapter(minuteContent));
               minuteWheel.setCurrentItem(curMinute);
               minuteWheel.setCyclic(false);
               minuteWheel.setInterpolator(new AnticipateOvershootInterpolator());

//	        builder.setTitle("起始时间");
               window.findViewById(R.id.cancel_btn).setOnClickListener(new View.OnClickListener() {

                   @Override
                   public void onClick(View v)
                   {
                       StringBuffer sb = new StringBuffer();
                       sb.append(yearWheel.getCurrentItemValue()).append("-")
                               .append(monthWheel.getCurrentItemValue()).append("-")
                               .append(dayWheel.getCurrentItemValue());

                       sb.append(" ");
                       sb.append(hourWheel.getCurrentItemValue())
                               .append(":").append(minuteWheel.getCurrentItemValue())
                       ;
                       timeText.setText(sb);

                       alertDialog.cancel();

                   }
               });


               break;


       }
    }

    private void upload() {
            if (isCanUpload()) {
                UpdateLoadInfo upload = new UpdateLoadInfo(useCarData);
                upload.execute();
            }
        
    }

    /*
      * 传送数据到服务器
      */
    private class UpdateLoadInfo extends AsyncTask<String, Integer, String> {
        UseCarData useCarDate;

        private MyLoadingDialog mydiog;

        public UpdateLoadInfo(UseCarData useCarDate) {

            this.useCarDate = useCarDate;
        }

        @Override
        protected void onPreExecute() {
            mydiog = new MyLoadingDialog(context, null, "提交中...", false);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            HttpResponse response = null;
            BufferedReader reader = null;
            try {

                MultipartEntity multipartEntity = new MultipartEntity();
                for (String fileuri : listfile) {
                    File file = new File(fileuri);
                    FileBody filebody = new FileBody(file, file.getName(), "application/octet-stream", "UTF-8");
                    multipartEntity.addPart(file.getName(), filebody);
                }

                multipartEntity.addPart("username", new StringBody(useCarData.getUserName(), Charset.forName("UTF-8")));
                multipartEntity.addPart("userId", new StringBody(useCarData.getUserId(), Charset.forName("UTF-8")));
                multipartEntity.addPart("destination", new StringBody( useCarData.getDestination(), Charset.forName("UTF-8")));
                multipartEntity.addPart("reason", new StringBody( useCarData.getReason(), Charset.forName("UTF-8")));
                multipartEntity.addPart("remark", new StringBody( useCarData.getRemark(), Charset.forName("UTF-8")));
                multipartEntity.addPart("predictMileage", new StringBody( useCarData.getPredictMileage()+"", Charset.forName("UTF-8")));
                multipartEntity.addPart("startDate", new StringBody( useCarData.getStartData(true), Charset.forName("UTF-8")));


                response = LinkHelp.UpPhotos(URLS.getOutStart(), multipartEntity, false);

                // ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
                // vs.add(new BasicNameValuePair("title",
                // paymentData.getTitle()));
                // vs.add(new BasicNameValuePair("type",
                // paymentData.getType()));
                // vs.add(new BasicNameValuePair("amount",
                // ""+paymentData.getAmount()));
                // vs.add(new BasicNameValuePair("bankName",
                // paymentData.getBankName()));
                // vs.add(new BasicNameValuePair("bankCardId",
                // paymentData.getBankCardId()));
                // vs.add(new BasicNameValuePair("gatheringManName",
                // paymentData.getGatheringManName()));
                //
                //
                // response = LinkHelp.post(URLS.getPaymentStart(), vs, false);

                if (response != null) {
                    StatusLine line = response.getStatusLine();
                    if (line.getStatusCode() == 200) {
                        reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                        StringBuilder sb = new StringBuilder();
                        for (String s = reader.readLine(); s != null; s = reader.readLine()) {
                            sb.append(s);
                        }
                        reader.close();
                        result = sb.toString();

                        System.out.println(result);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            mydiog.dimiss();
            if (result != null) {
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(result);
                    if (jsonObject.isNull("code")) {
                        String status = jsonObject.getString("status");
                        UserInfo info = UserInfo.getUserInfor();
                        if (status.equals("success")) {
                            Toast.makeText(context, "提交成功", Toast.LENGTH_SHORT).show();

                            finish();
                        } else {
                            String msg = jsonObject.getString("msg");
                            // Toast.makeText(context, msg,
                            // Toast.LENGTH_SHORT).show();
                            ToastHelp.doToastInTop(context, msg);
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                ToastHelp.doToastInTop(context, "网络异常");
            }

        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {

                case MenuActivity.SELECT_PHOTO:
                    // ArrayList<String> files =new ArrayList<String>();
                    listfileCatch.clear();
                    listfileCatch = data.getStringArrayListExtra("files");
                    listfile.addAll(listfileCatch);
                    initGridView();
                    break;

                default:
                    break;
            }
        }
    }

    private void initGridView() {
        new AsyncLoadedImage().execute();

    }

    /*
    * 异步加载缩略图到LoadedImage然后调用addImage方法更新Adapter
    */
    class AsyncLoadedImage extends AsyncTask<Object, LoadedImage, Object> {
        @Override
        protected Object doInBackground(Object... params) {

            Bitmap bitmap = null;
            Bitmap newBitmap;
            for (int i = 0; i < listfileCatch.size(); i++) {
                String path = listfileCatch.get(i);

                File file = new File(path);
                if (file.exists()) {
                    System.out.println(path + "存在");
                    if (FileUtils.isPic(path)) {

                        try {
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inSampleSize = 10;
                            bitmap = BitmapFactory.decodeFile(path, options);
                            newBitmap = ThumbnailUtils.extractThumbnail(bitmap, 120, 120);
                            bitmap.recycle();
                            if (newBitmap != null) {
                                publishProgress(new LoadedImage(newBitmap, path));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
                        try {

                            if (path.contains(".pdf")) {
                                bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pdf);
                            } else if (path.contains(".txt")) {
                                bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.text);
                            } else if (path.contains(".doc")) {
                                bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.word);
                            } else if (path.contains(".zip")) {
                                bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.zip);
                            } else if (path.contains(".xls")) {
                                bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.excel);
                            } else {
                                bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.file);
                            }
                            newBitmap = ThumbnailUtils.extractThumbnail(bitmap, 120, 120);
                            bitmap.recycle();
                            if (newBitmap != null) {
                                publishProgress(new LoadedImage(newBitmap, path));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                } else {
                    listfile.remove(path);
                }

            }

            return null;
        }

        // 实时更新UI
        // onProgressUpdate()方法的参数对应于doInBackground中publishProgress方法的参数，同时也对应于
        // doInBackground的第二个参数
        @Override
        public void onProgressUpdate(LoadedImage... value) {
            addImage(value);
        }

        // 更新UI结束后的处理
        @Override
        protected void onPostExecute(Object result) {
            setProgressBarIndeterminateVisibility(false);
        }
    }

    /*
    * 刷新Adapter
    */
    private void addImage(LoadedImage... value) {
        for (LoadedImage image : value) {
            fileAdapter.addPhoto(image);
            fileAdapter.notifyDataSetChanged();
            gridview.setVisibility(View.VISIBLE);
        }
    }
}
